<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: Page.php 2010-08-31 16:05 idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Page_Model_Page extends Core_Model_Item_Abstract {
	protected $_parent_type = 'user';
	
	protected $_owner_type = 'user';
	
	protected $_content_info;
	
	public $owner;
	
	protected $_searchColumns = array ('search', 'title', 'description' );
	
	protected $_modifiedTriggers = array ();
	
	public function init() {
		$this->owner = Engine_Api::_ ()->getItem ( 'user', $this->user_id );
	}
	
	public function likes() {
		return new Engine_ProxyObject ( $this, Engine_Api::_ ()->getDbtable ( 'likes', 'core' ) );
	}
	
	public function comments() {
		return new Engine_ProxyObject ( $this, Engine_Api::_ ()->getDbtable ( 'comments', 'core' ) );
	}
	
	public function setContentInfo($content, $content_id) {
		$this->_content_info = array ('content' => $content, 'content_id' => $content_id );
	}
	
	public function getContentInfo() {
		return $this->_content_info;
	}
	
	public function getDescription($truncate = false, $strip_tags = true, $nl2br = true, $truncate_count = 200) {
		$description = $this->description;
		if ($strip_tags) {
			$description = strip_tags ( $description );
		}
		
		if ($truncate) {
			$description = Engine_Api::_ ()->getApi ( 'core', 'hecore' )->truncate ( $description, $truncate_count );
		}
		
		if ($nl2br) {
			$description = nl2br ( $description );
		}
		
		return $description;
	}
	
	public function isTeamMember($viewer = null) {
		if ($viewer === null) {
			$viewer = Engine_Api::_ ()->user ()->getViewer ();
		} elseif (is_numeric ( $viewer )) {
			$viewer = Engine_Api::_ ()->getItem ( 'user', $viewer );
		}
		
		if (! ($viewer instanceof Core_Model_Item_Abstract)) {
			return false;
		}
		
		return ($this->membership ()->isMember ( $viewer, true ) || $this->user_id == $viewer->getIdentity ());
	}
	
	public function isExists($page_id = null) {
		if ($page_id == null) {
			$page_id = $this->page_id;
		}
		
		return ( bool ) Engine_Api::_ ()->getItem ( 'page', $page_id );
	}
	
	public function getAddress() {
		$address = array ();
		if ($this->country) {
			$address [] = $this->country;
		}
		if ($this->city) {
			$address [] = $this->city;
		}
		if ($this->street) {
			$address [] = $this->street;
		}
		
		return implode ( ", ", $address );
	}
	
	public function getAdmins($limit = 0) {
		$table = Engine_Api::_ ()->getDbtable ( 'users', 'user' );
		$tableName = $table->info ( 'name' );
		
		$select = $table->select ()->setIntegrityCheck ( false );
		
		$prefix = $table->getTablePrefix ();
		
		$select->from ( $tableName )->joinLeft ( $prefix . "page_membership", $prefix . "page_membership.user_id = {$tableName}.user_id", array ('title' ) )->where ( $prefix . "page_membership.resource_id = {$this->getIdentity()}" )->limit ( $limit );
		
		return Zend_Paginator::factory ( $select );
	}
	
	public function getWebsite() {
		if (! strpos ( $this->website, "http://" )) {
			$url = "http://" . $this->website;
		} else {
			$url = $this->website;
		}
		
		return "<a href='" . $url . "' target='_blank'>" . $this->website . "</a>";
	}
	
	public function isAddress() {
		if ($this->country || $this->city || $this->street) {
			return true;
		}
		
		return false;
	}
	
	public function getHref($params = array()) {
		$params = array_merge ( array ('route' => 'page_view', 'reset' => true, 'page_id' => $this->url ), $params );
		
		$route = $params ['route'];
		$reset = $params ['reset'];
		unset ( $params ['route'] );
		unset ( $params ['reset'] );
		
		return Zend_Controller_Front::getInstance ()->getRouter ()->assemble ( $params, $route, $reset );
	}
	
	public function removePhotos() {
		if (isset ( $this->photo_id ) && $this->photo_id != 0) {
			$storage = Engine_Api::_ ()->storage ();
			$file = $storage->get ( $this->photo_id );
			if ($file !== null)
				$file->remove ();
			$file = $storage->get ( $this->photo_id, 'thumb.normal' );
			if ($file !== null)
				$file->remove ();
			$file = $storage->get ( $this->photo_id, 'thumb.icon' );
			if ($file !== null)
				$file->remove ();
		}
	}
	
	public function setPhoto($photo) {
		if ($photo instanceof Zend_Form_Element_File) {
			$file = $photo->getFileName ();
		} else if (is_array ( $photo ) && ! empty ( $photo ['tmp_name'] )) {
			$file = $photo ['tmp_name'];
		} else if (is_string ( $photo ) && file_exists ( $photo )) {
			$file = $photo;
		} else {
			throw new Event_Model_Exception ( 'invalid argument passed to setPhoto' );
		}
		
		$name = basename ( $file );
		$path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary';
		$params = array ('parent_id' => $this->getIdentity (), 'parent_type' => 'page' );
		
		// Remove photos
		$this->removePhotos ();
		
		// Save
		$storage = Engine_Api::_ ()->storage ();
		
		// Resize image (main)
		$image = Engine_Image::factory ();
		$image->open ( $file )->resize ( 175, 200 )->write ( $path . '/m_' . $name )->destroy ();
		
		// Resize image (normal)
		$image = Engine_Image::factory ();
		$image->open ( $file )->resize ( 140, 160 )->write ( $path . '/in_' . $name )->destroy ();
		
		// Resize image (icon)
		$image = Engine_Image::factory ();
		$image->open ( $file );
		
		$size = min ( $image->height, $image->width );
		$x = ($image->width - $size) / 2;
		$y = ($image->height - $size) / 2;
		
		$image->resample ( $x, $y, $size, $size, 48, 48 )->write ( $path . '/is_' . $name )->destroy ();
		
		// Store
		$iMain = $storage->create ( $path . '/m_' . $name, $params );
		$iIconNormal = $storage->create ( $path . '/in_' . $name, $params );
		$iSquare = $storage->create ( $path . '/is_' . $name, $params );
		
		$iMain->bridge ( $iIconNormal, 'thumb.normal' );
		$iMain->bridge ( $iSquare, 'thumb.icon' );
		
		// Update row
		$this->modified_date = date ( 'Y-m-d H:i:s' );
		$this->photo_id = $iMain->file_id;
		$this->save ();
		
		return $this;
	}
	
	public function isAddressChanged($address) {
		if (! is_array ( $address ) || empty ( $address )) {
			return false;
		}
		
		return (($this->country != $address [0] || $this->city != $address [1] || $this->street != $address [2]));
	}
	
	public function setPrivacy(array $values) {
		$auth = Engine_Api::_ ()->authorization ()->context;
		
		$roles = array ('team', 'likes', 'registered', 'everyone' );
		$viewMax = array_search ( $values ['auth_view'], $roles );
		foreach ( $roles as $i => $role ) {
			if ($role === 'team') {
				$role = $this->getTeamList ();
			} elseif ($role === 'likes') {
				$role = $this->getLikesList ();
			}
			$auth->setAllowed ( $this, $role, 'view', ( int ) ($i <= $viewMax) );
		}
		
		$roles = array ('team', 'likes', 'registered' );
		$commentMax = array_search ( $values ['auth_comment'], $roles );
		foreach ( $roles as $i => $role ) {
			if ($role === 'team') {
				$role = $this->getTeamList ();
			} elseif ($role === 'likes') {
				$role = $this->getLikesList ();
			}
			$auth->setAllowed ( $this, $role, 'comment', ( int ) ($i <= $commentMax) );
		}
		
		$roles = array ('team', 'likes', 'registered' );
		$postingMax = array_search ( $values ['auth_posting'], $roles );
		foreach ( $roles as $i => $role ) {
			if ($role === 'team') {
				$role = $this->getTeamList ();
			} elseif ($role === 'likes') {
				$role = $this->getLikesList ();
			}
			$auth->setAllowed ( $this, $role, 'posting', ( int ) ($i <= $postingMax) );
		}
		
		if ($values ['auth_view'] == 'registered' || $values ['auth_view'] == 'everyone') {
			$auth->setAllowed ( $this, $this->getLikesList (), 'view', 1 );
		}
		
		if ($values ['auth_comment'] == 'registered') {
			$auth->setAllowed ( $this, $this->getLikesList (), 'comment', 1 );
		}
		
		if ($values ['auth_posting'] == 'registered') {
			$auth->setAllowed ( $this, $this->getLikesList (), 'posting', 1 );
		}
		
		$auth->setAllowed ( $this, $this->getTeamList (), 'view', 1 );
		$auth->setAllowed ( $this, $this->getTeamList (), 'comment', 1 );
		$auth->setAllowed ( $this, $this->getTeamList (), 'posting', 1 );
	}
	
	public function getTeamList() {
		$table = Engine_Api::_ ()->getDbTable ( 'lists', 'page' );
		$select = $table->select ()->where ( 'owner_id = ?', $this->getIdentity () )->where ( 'title = ?', 'PAGE_TEAM' )->limit ( 1 );
		
		$list = $table->fetchRow ( $select );
		
		if (null === $list) {
			$list = $table->createRow ();
			$list->setFromArray ( array ('owner_id' => $this->getIdentity (), 'title' => 'PAGE_TEAM' ) );
			$list->save ();
		}
		
		return $list;
	}
	
	public function getLikesList() {
		$table = Engine_Api::_ ()->getDbTable ( 'lists', 'page' );
		$select = $table->select ()->where ( 'owner_id = ?', $this->getIdentity () )->where ( 'title = ?', 'PAGE_LIKES' )->limit ( 1 );
		
		$list = $table->fetchRow ( $select );
		
		if (null === $list) {
			$list = $table->createRow ();
			$list->setFromArray ( array ('owner_id' => $this->getIdentity (), 'title' => 'PAGE_LIKES' ) );
			$list->save ();
		}
		
		return $list;
	}
	
	public function membership() {
		return new Engine_ProxyObject ( $this, Engine_Api::_ ()->getDbTable ( 'membership', 'page' ) );
	}
	
	public function addMarker(Page_Model_Marker $marker) {
		$marker->getTable ()->delete ( "page_id = {$this->page_id}" );
		
		$marker->page_id = $this->page_id;
		$marker->save ();
	}
	
	public function addMarkerByAddress($address) {
		$marker = Engine_Api::_ ()->getApi ( 'gmap', 'page' )->getMarker ( $address );
		if ($marker) {
			$this->addMarker ( $marker );
		}
	}
	
	public function deleteMarker() {
		Engine_Api::_ ()->getApi ( 'gmap', 'page' )->deleteMarker ( $this );
	}
	
	public function createContent() {
		$contentTable = Engine_Api::_ ()->getDbtable ( 'content', 'page' );
		$contentRow = $this->createContentItem ( array ('type' => 'container', 'order' => 2, 'name' => 'main', 'parent_content_id' => 0 ) );
		$contentRow2 = $this->createContentItem ( array ('type' => 'container', 'order' => 6, 'name' => 'middle', 'parent_content_id' => $contentRow->content_id ) );
		$contentRow3 = $this->createContentItem ( array ('type' => 'container', 'order' => 4, 'name' => 'left', 'parent_content_id' => $contentRow->content_id ) );
		
		$contentRow4 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"max":"8"}', 'order' => 12, 'name' => 'core.container-tabs', 'parent_content_id' => $contentRow2->content_id ) );
		$contentRow5 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Photo", "titleCount":false}', 'order' => 3, 'name' => 'page.profile-photo', 'parent_content_id' => $contentRow3->content_id ) );
		$contentRow6 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Options", "titleCount":false}', 'order' => 4, 'name' => 'page.profile-options', 'parent_content_id' => $contentRow3->content_id ) );
		
		$table = Engine_Api::_ ()->getDbTable ( 'modules', 'core' );
		if ($table->isModuleEnabled ( 'rate' )) {
			$contentRow6 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Rate", "titleCount":false}', 'order' => 5, 'name' => 'rate.widget-rate', 'parent_content_id' => $contentRow3->content_id ) );
		}
		
		$contentRow7 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Note", "titleCount":false}', 'order' => 6, 'name' => 'page.profile-note', 'parent_content_id' => $contentRow3->content_id ) );
		$contentRow8 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Map", "titleCount":false}', 'order' => 7, 'name' => 'page.profile-map', 'parent_content_id' => $contentRow3->content_id ) );
		$contentRow9 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Team", "titleCount":true}', 'order' => 8, 'name' => 'page.profile-admins', 'parent_content_id' => $contentRow3->content_id ) );
		$contentRow10 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"like_Like Club", "titleCount":true}', 'order' => 9, 'name' => 'like.box', 'parent_content_id' => $contentRow3->content_id ) );
		$contentRow14 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Tag Cloud", "titleCount":false}', 'order' => 10, 'name' => 'page.tag-cloud', 'parent_content_id' => $contentRow3->content_id ) );
		
		$contentRow10 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Updates"}', 'order' => 13, 'name' => 'page.feed', 'parent_content_id' => $contentRow4->content_id ) );
		$contentRow11 = $this->createContentItem ( array ('type' => 'widget', 'params' => '{"title":"Info"}', 'order' => 14, 'name' => 'page.profile-fields', 'parent_content_id' => $contentRow4->content_id ) );
		
		$contentRow13 = $this->createContentItem ( array ('type' => 'widget', 'order' => 11, 'name' => 'page.search', 'parent_content_id' => $contentRow2->content_id ) );
		$contentRow12 = $this->createContentItem ( array ('type' => 'widget', 'order' => 10, 'name' => 'like.status', 'parent_content_id' => $contentRow2->content_id ) );
		
		$db = $table->getAdapter ();
		
		$prefix = $table->getTablePrefix ();
		
		$select = $db->select ()->from ( $prefix . 'page_modules' );
		$modules = $db->fetchAll ( $select );
		
		foreach ( $modules as $module ) {
			if (! $table->isModuleEnabled ( $module ['name'] ))
				continue;
			$contentRow13 = $this->createContentItem ( array ('type' => 'widget', 'params' => $module ['params'], 'order' => $module ['order'], 'name' => $module ['widget'], 'parent_content_id' => $contentRow4->content_id ) );
		}
	}
	
	public function createContentItem(Array $params) {
		if (empty ( $params )) {
			return false;
		}
		$contentTable = $params ['table'];
		if (! $contentTable) {
			$contentTable = Engine_Api::_ ()->getDbtable ( 'content', 'page' );
		}
		
		$contentRow = $contentTable->createRow ();
		foreach ( $params as $key => $value ) {
			if ($key == "") {
				continue;
			}
			if ($value === null) {
				$value = "";
			}
			$contentRow->$key = $value;
		}
		$contentRow->page_id = $this->page_id;
		$contentRow->save ();
		
		return $contentRow;
	}
	
	protected function _delete() {
		$this->removePhotos ();
		$page_id = $this->getIdentity ();
		
		$table = Engine_Api::_ ()->fields ()->getTable ( 'page', 'search' );
		$prefix = $table->getTablePrefix ();
		
		$db = $table->getAdapter ();
		$db->delete ( $prefix . 'page_fields_search', "item_id = {$page_id}" );
		$db->delete ( $prefix . 'page_fields_values', "item_id = {$page_id}" );
		$db->delete ( $prefix . 'page_markers', "page_id = {$page_id}" );
		$db->delete ( $prefix . 'page_content', "page_id = {$page_id}" );
		$db->delete ( $prefix . 'page_views', "page_id = {$page_id}" );
		
		$where = "object_id = {$page_id} AND object_type = 'page'";
		
		$db->delete ( $prefix . 'activity_actions', $where );
		$db->delete ( $prefix . 'activity_stream', $where );
		
		$where = "resource_type = 'page' AND resource_id = {$page_id}";
		
		$db->delete ( $prefix . 'core_tagmaps', $where );
		$db->delete ( $prefix . 'authorization_allow', $where );
		
		$teamList = $this->getTeamList ();
		$likesList = $this->getLikesList ();
		
		$db->delete ( $prefix . 'page_listitems', "list_id = {$teamList->getIdentity()}" );
		$db->delete ( $prefix . 'page_listitems', "list_id = {$likesList->getIdentity()}" );
		
		$db->delete ( $prefix . 'page_lists', "owner_id = {$this->page_id}" );
		
		$like_club = Engine_Api::_ ()->like ()->getLikeClub ( $this );
		if ($like_club) {
			$like_club->delete ();
		}
		
		$this->membership ()->removeAllMembers ();
		Engine_Hooks_Dispatcher::getInstance ()->callEvent ( 'removePage', array ('page' => $this ) );
		
		parent::_delete ();
	}
	
	public function fields() {
		return new Engine_ProxyObject ( $this, $this->api ()->getApi ( 'core', 'fields' ) );
	}
	
	public function approvedStatus($value) {
		$this->approved = $value;
		$this->save ();
		
		return $this;
	}
	
	public function featuredStatus($value) {
		$this->featured = $value;
		$this->save ();
		
		return $this;
	}
	
	public function setIdentity($id) {
		$this->_identity = $id;
		
		return $this;
	}
	
	public function viewPage() {
		$user_id = ( int ) Engine_Api::_ ()->user ()->getViewer ()->getIdentity ();
		$today = Engine_Api::_ ()->page ()->getToday ();
		$table = Engine_Api::_ ()->getDbTable ( 'views', 'page' );
		
		$view = $table->createRow ();
		
		if ($user_id == $this->user_id) {
			return;
		}
		
		$db = $table->getAdapter ();
		$prefix = $table->getTablePrefix ();
		
		$select = $db->select ();
		$select->from ( $prefix . 'page_views', array ('view_id' ) )->where ( 'page_id = ?', $this->page_id )->where ( 'view_date >= ?', $today )->where ( 'user_id = ?', $user_id );
		
		$ip = ip2long ( $_SERVER ['REMOTE_ADDR'] );
		$select->where ( 'ip = ?', $ip );
		
		$view->user_id = $user_id;
		$view->ip = $ip;
		
		if (! (( bool ) $db->fetchOne ( $select ))) {
			$this->unique_views ++;
		}
		
		$view->view_date = $today;
		$view->page_id = $this->page_id;
		$view->save ();
		
		$this->view_count ++;
		$this->save ();
	}
	
	public function tags() {
		return new Engine_ProxyObject ( $this, Engine_Api::_ ()->getDbtable ( 'tags', 'core' ) );
	}
	
	public function getTotalVisitorsCount() {
		return $this->unique_views;
	}
	
	public function getTotalViewsCount() {
		return $this->view_count;
	}
	
	public function displayAddress() {
		$address = array ();
		
		if (! empty ( $this->city )) {
			$address [] = $this->city;
		}
		
		if (! empty ( $this->country )) {
			$address [] = $this->country;
		}
		
		if (! empty ( $this->street )) {
			$address [] = $this->street;
		}
		
		return implode ( ', ', $address );
	}
	
	public function getViewStats($params) {
		$select = $this->getViewStatsSelect ( $params );
		return Zend_Paginator::factory ( $select );
	}
	
	public function getViewStatsCount($params) {
		$select = $this->getViewStatsSelect ( $params );
		$db = $this->getTable ()->getAdapter ();
		
		$query = "SELECT SUM(count) FROM (" . $select->__toString () . ") AS t1";
		return $db->fetchOne ( $query );
	}
	
	public function getViewStatsSelect($params) {
		$table = $this->getTable ();
		$db = $table->getAdapter ();
		
		$prefix = $table->getTablePrefix ();
		
		$select = $db->select ();
		
		$select->from ( $prefix . 'page_views', array () )->joinLeft ( $prefix . 'page_locations', $prefix . 'page_views.ip BETWEEN ' . $prefix . 'page_locations.begin_num AND ' . $prefix . 'page_locations.end_num', array ('count' => 'COUNT(DISTINCT user_id, ip)', 'country', 'name' ) )->where ( $prefix . 'page_views.page_id = ?', $this->getIdentity () )->where ( $prefix . 'page_locations.country IS NOT NULL' )->group ( $prefix . 'page_locations.country' );
		
		return $select;
	}
	
	public function getLikesCount() {
		if (Engine_Api::_ ()->page ()->isModuleExists ( 'like' )) {
			$likeApi = Engine_Api::_ ()->getApi ( 'core', 'like' );
			return ( int ) $likeApi->getLikeCount ( $this );
		}
		
		return 0;
	}
	
	public function getParent($type) {
		return $this->getOwner ( $type );
	}

}